﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace 控制台数据流输出
{
    /// <summary>
    ///用于输出到网络流
    /// </summary>
    public class NetWorkStreamWriter : StreamWriter
    {

        #region 构造函数


        /// <summary>
        ///  用 UTF-8 编码及默认缓冲区大小，为指定的流初始化 System.IO.StreamWriter 类的一个新实例。
        /// </summary>
        /// <param name="stream">要写入的流</param>
        public NetWorkStreamWriter(Stream stream) : base(stream) { Gb2312 = System.Text.Encoding.GetEncoding("GB2312"); }

        public NetWorkStreamWriter(Stream stream, Encoding encoding)
            : base(stream, encoding)
        {
            Gb2312 = System.Text.Encoding.GetEncoding("GB2312");
        }

        public NetWorkStreamWriter(string path) : base(path) { Gb2312 = System.Text.Encoding.GetEncoding("GB2312"); }
        #endregion

        /// <summary>
        /// 用于辅助异步发送Socket数据类对像
        /// </summary>
        protected AsyncSocketSendHelper socketSendAsync = new AsyncSocketSendHelper();

        /// <summary>
        /// 输出网络流
        /// </summary>
        public Socket NetworkOutPutSocket { get; set; }

        protected Encoding Gb2312 = null;
        /// <summary>
        /// 异步发送数据
        /// </summary>
        /// <param name="strs"></param>
        protected void SendAsync(string strs)
        {
            if (NetworkOutPutSocket != null)
            {
                try
                {
                    if (NetworkOutPutSocket.Connected)
                    {

                        //异步发送数据
                        socketSendAsync.SendToAsync(NetworkOutPutSocket, Gb2312.GetBytes(strs));

                    }
                }
                catch (NullReferenceException ex)
                {

                }
                catch (SocketException ex)
                {

                }
                catch (ObjectDisposedException ex)
                {

                }
            }


        }

        public override void Flush()
        {
            base.Flush();
        }


        public override Task FlushAsync()
        {
            return base.FlushAsync();
        }
        public override void WriteLine(string value)
        {
            SendAsync(value + "\r\n");
            base.WriteLine(value);
            Flush();
        }

        public override void Write(string value)
        {
            SendAsync(value);
            base.Write(value);
            Flush();
        }

    }
}
